import os
import re
import json


def find_gn_files(root_dir):
    gn_files = []
    for dirpath, dirnames, filenames in os.walk(root_dir):
        for filename in filenames:
            if filename.endswith('.gn'):
                gn_files.append((os.path.join(dirpath, filename), dirpath))
    return gn_files


def extract_part_name(file_path):
    part_name_pattern = re.compile(r'part_name\s*=\s*"([^"]+)"')
    with open(file_path, 'r') as file:
        content = file.read()
        match = part_name_pattern.search(content)
        if match:
            return match.group(1)
    return None


def main(root_dir, base_dir):
    gn_files = find_gn_files(root_dir)
    results = {}

    for file_path, dir_path in gn_files:
        rel_dir_path = os.path.relpath(dir_path, base_dir)

        part_name = extract_part_name(file_path)
        if part_name:
            if part_name in results:
                if isinstance(results[part_name], list):
                    results[part_name].append(rel_dir_path)
                else:
                    results[part_name] = [results[part_name], rel_dir_path]
            else:
                results[part_name] = rel_dir_path

    for key in results:
        if not isinstance(results[key], list):
            results[key] = [results[key]]

    with open('results.json', 'w') as json_file:
        json.dump(results, json_file, indent=4)

    print("Results have been saved to results.json")


if __name__ == "__main__":
    root_directory = '/home/user/OH/openHarmonyMaster/test/xts/acts'
    base_directory = '/home/user/OH/openHarmonyMaster/test/xts/acts'
    main(root_directory, base_directory)